package com.xq.operation;

import com.xq.pojo.User;
import com.xq.utils.CustomSerializer;
import com.xq.utils.ObjectSerializer;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;

import java.io.IOException;
import java.util.List;

/**
 * 单机版连接ZK，对数据的订阅监控
 * @author 卡布奇诺
 */
public class TestZkServerSubData {
    /**
     * ZK连接URL
     */
    private static final String SERVER_IP = "192.168.2.120:2190";

    /**
     * zk客户端对象
     */
    private static ZkClient zkClient = null;

    static {
        // 初始化zk客户端对象
        zkClient = new ZkClient(SERVER_IP,10000,10000,new CustomSerializer());
    }

    public static void main( String[] args ) throws IOException {
        // 创建节点
        //zkClient.create("/sub1","sub1", CreateMode.PERSISTENT);
        //zkClient.create("/sub2","sub2", CreateMode.PERSISTENT);
        // zkClient.create("/sub3","sub3", CreateMode.PERSISTENT);

        // 监听节点的修改和删除操作
        zkClient.subscribeDataChanges("/sub1", new IZkDataListener() {
            /**
             * 监听该节点的修改
             * @param dataPath 节点路径
             * @param data 节点数据
             */
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println("节点数据发生变化，节点路径：" + dataPath + "，节点的数据："+data);
            }

            /**
             * 监听该节点的删除
             * @param dataPath 节点路径
             */
            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("节点数据发生删除，节点路径：" + dataPath);
            }
        });

        // 监听子节点的数据的添加或删除
        zkClient.subscribeChildChanges("/subP1/subC1", new IZkChildListener() {
            /**
             * 监听子节点的数据的添加或删除
             * @param parentPath 父节点路径
             * @param currentChilds 子节点
             * @throws Exception
             */
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                System.out.println("父节点路径：" + parentPath);
                System.out.println("改变后的子节点的数据：");
                currentChilds.stream().forEach(i -> {
                    System.out.println(i);
                });
            }
        });

        // 阻塞程序
        System.in.read();
        System.out.println("操作成功ZkClient");
    }
}
